package J20250330_real;

/**
 * Created with IntelliJ IDEA.
 * Description: 穿越雷区——https://www.lanqiao.cn/problems/141/learning/?page=1&first_category_id=1&difficulty=20
 * User: 王圆豪
 * Date: 2025-04-11
 * Time: 19:00
 */


import java.util.*;

public class Main15 {
    static int[] dx = {1,-1,0,0};
    static int[] dy = {0,0,-1,1};
    static boolean[][] vis;
    static boolean flag = false;
    static int ret = Integer.MAX_VALUE;
    static int path = 0;
    static int sx = 0, sy = 0, ex = 0,ey = 0;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        char[][] flied = new char[n][n];
        vis = new boolean[n][n];
        for(int i =0 ; i < n; i++) {
            String s = sc.nextLine();
            for(int j = 0,k=0; j < n&&k<s.length(); j++,k+=2) {
                flied[i][j] = s.charAt(k);
                if(flied[i][j] == 'A') {
                    sx = i;
                    sy = j;
                }else if(flied[i][j] == 'B') {
                    ex = i;
                    ey = j;
                }
            }
        }
//		for(int i = 0; i < n; i++) {
//			for(int j = 0; j < n; j++) {
//				System.out.print(flied[i][j]);
//			}
//			System.out.println();
//		}
        for(int i = 0; i < 4; i++) {
            int x = sx+dx[i], y = sy+dy[i];
            if(x<n&&x>=0&&y>=0&&y<n) {
                vis[x][y] = true;
                path++;
                dfs(x,y,flied,flied[x][y]=='-'?'+':'-');
                path--;
                vis[x][y] = false;
            }
        }
        System.out.println(flag?ret:-1);
        sc.close();
    }

    static void dfs(int x, int y, char[][] flied, char judge) {
        if(x == ex && y == ey) {
            flag = true;
            ret = Math.min(ret, path);
            return;
        }
        for(int i = 0; i < 4; i++) {
            int px = x + dx[i], py = y + dy[i];
            if(px>=0&&px<flied.length&&py>=0&&py<flied.length&&!vis[px][py]&&(flied[px][py]==judge||flied[px][py]=='B')) {
                vis[px][py] = true;
                path++;
                dfs(px,py,flied,flied[px][py]=='-'?'+':'-');
                path--;
                vis[px][py] = false;
            }
        }
    }
}

